"""
剪映小助手自动化控制器
提供剪映小助手的自动化操作功能，用于下载网络草稿
"""

import time
import logging
import traceback
from datetime import datetime
from typing import Dict, Any, Optional
import win32gui
import win32con
import uiautomation as uia
import pyperclip
import pythoncom
from threading import current_thread
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError


class JianyingHelperController:
    """剪映小助手自动化控制器"""

    def __init__(self):
        self.target_window = None
        self.uia_window = None
        self._com_initialized_threads = set()

        # 配置日志
        self.logger = logging.getLogger(__name__)
        if not self.logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
            self.logger.setLevel(logging.DEBUG)

    def _ensure_com_initialized(self):
        """确保当前线程已初始化COM（防护式初始化）"""
        thread_id = current_thread().ident
        if thread_id not in self._com_initialized_threads:
            try:
                # 检查是否已经初始化
                try:
                    pythoncom.CoGetCurrentProcess()
                    self._com_initialized_threads.add(thread_id)
                    self.logger.info(f"线程 {thread_id} COM已经初始化")
                    return
                except:
                    pass

                # 使用单线程套间模式初始化COM，避免多进程冲突
                pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
                self._com_initialized_threads.add(thread_id)
                self.logger.info(f"线程 {thread_id} COM初始化成功（单线程套间模式）")
            except Exception as e:
                self.logger.warning(f"线程 {thread_id} COM初始化失败: {e}")
                # 作为后备，尝试标准初始化
                try:
                    pythoncom.CoInitialize()
                    self._com_initialized_threads.add(thread_id)
                    self.logger.info(f"线程 {thread_id} COM后备初始化成功")
                except:
                    self.logger.error(f"线程 {thread_id} COM初始化完全失败")

    def _cleanup_com(self):
        """清理当前线程的COM"""
        thread_id = current_thread().ident
        if thread_id in self._com_initialized_threads:
            try:
                pythoncom.CoUninitialize()
                self._com_initialized_threads.remove(thread_id)
                self.logger.info(f"线程 {thread_id} COM清理成功")
            except Exception as e:
                self.logger.warning(f"线程 {thread_id} COM清理失败: {e}")

    def find_window(self) -> bool:
        """查找剪映小助手窗口"""
        self._ensure_com_initialized()

        def enum_windows_callback(hwnd, windows):
            if win32gui.IsWindowVisible(hwnd):
                window_text = win32gui.GetWindowText(hwnd)
                class_name = win32gui.GetClassName(hwnd)
                if window_text:
                    windows.append((hwnd, window_text, class_name))
            return True

        windows = []
        win32gui.EnumWindows(enum_windows_callback, windows)

        self.logger.info(f"找到 {len(windows)} 个可见窗口")

        # 查找剪映小助手
        for hwnd, title, class_name in windows:
            if '剪映小助手' in title or '小助手' in title:
                self.logger.info(f"找到剪映小助手窗口: {title} (类名: {class_name})")
                self.target_window = hwnd
                try:
                    self.uia_window = uia.ControlFromHandle(hwnd)
                    if self.uia_window:
                        self.logger.info("成功创建UIAutomation控制对象")
                        return True
                except Exception as e:
                    self.logger.error(f"创建UIAutomation控制对象失败: {e}")
                    continue

        # 查找所有Chrome应用（不限制标题）
        chrome_windows = [(hwnd, title, class_name) for hwnd, title, class_name in windows
                         if class_name == 'Chrome_WidgetWin_1']

        self.logger.info(f"找到 {len(chrome_windows)} 个Chrome应用窗口")
        for hwnd, title, class_name in chrome_windows:
            self.logger.info(f"  Chrome窗口: {title}")

        # 优先选择包含小助手/剪映的窗口
        target_chrome = None
        for hwnd, title, class_name in chrome_windows:
            if '小助手' in title or '剪映' in title:
                target_chrome = (hwnd, title, class_name)
                break

        # 如果没找到明确的，选择第一个Chrome窗口
        if not target_chrome and chrome_windows:
            target_chrome = chrome_windows[0]

        if target_chrome:
            hwnd, title, class_name = target_chrome
            self.logger.info(f"使用Chrome应用窗口: {title}")
            self.target_window = hwnd
            try:
                self.uia_window = uia.ControlFromHandle(hwnd)
                if self.uia_window:
                    self.logger.info("成功创建Chrome应用UIAutomation控制对象")
                    return True
            except Exception as e:
                self.logger.error(f"创建Chrome应用UIAutomation控制对象失败: {e}")
                pass

        self.logger.error("未找到剪映小助手窗口")
        return False

    def activate_window(self) -> bool:
        """激活窗口"""
        if not self.target_window:
            self.logger.error("目标窗口句柄为空")
            return False

        try:
            # 检查窗口是否存在
            if not win32gui.IsWindow(self.target_window):
                self.logger.error("窗口句柄无效")
                return False

            window_title = win32gui.GetWindowText(self.target_window)
            self.logger.info(f"尝试激活窗口: {window_title}")

            # 检查窗口是否最小化
            if win32gui.IsIconic(self.target_window):
                self.logger.info("窗口已最小化，正在恢复...")
                win32gui.ShowWindow(self.target_window, win32con.SW_RESTORE)
                time.sleep(0.5)

            # 显示窗口
            win32gui.ShowWindow(self.target_window, win32con.SW_SHOW)
            time.sleep(0.3)

            # 尝试设置前台窗口
            try:
                win32gui.SetForegroundWindow(self.target_window)
                self.logger.info("成功设置为前台窗口")
            except Exception as e:
                self.logger.warning(f"SetForegroundWindow失败: {e}，尝试其他方法")
                # 尝试使用BringWindowToTop
                win32gui.BringWindowToTop(self.target_window)
                # 设置窗口为活动窗口
                win32gui.SetActiveWindow(self.target_window)

            time.sleep(1.0)

            # 验证窗口是否成功激活
            foreground_window = win32gui.GetForegroundWindow()
            if foreground_window == self.target_window:
                self.logger.info("窗口激活成功")
                return True
            else:
                self.logger.warning(f"窗口可能未完全激活，前台窗口: {win32gui.GetWindowText(foreground_window)}")
                return True  # 继续执行，可能仍然可用

        except Exception as e:
            self.logger.error(f"激活窗口异常: {e}")
            self.logger.error(f"异常详情: {traceback.format_exc()}")
            return False

    def find_controls(self, retry_count=3, wait_time=3.0):
        """查找formUrl输入框和创建按钮"""
        if not self.uia_window:
            self.logger.error("UIAutomation窗口对象为空")
            return None, None

        for attempt in range(retry_count):
            self.logger.info(f"第 {attempt + 1} 次尝试查找控件...")

            input_controls = []
            button_controls = []

            def find_recursive(control, depth=0, max_depth=20):
                if depth > max_depth:
                    return

                try:
                    control_type = control.ControlType
                    control_name = getattr(control, 'Name', '') or ''
                    auto_id = getattr(control, 'AutomationId', '') or ''
                    is_enabled = getattr(control, 'IsEnabled', True)

                    # 调试信息：记录所有找到的控件
                    if depth <= 5:  # 只记录前几层的详细信息
                        self.logger.debug(f"深度{depth}: {control_type} - 名称:'{control_name}' - ID:'{auto_id}' - 启用:{is_enabled}")

                    # 查找formUrl输入框
                    if auto_id == 'formUrl':
                        self.logger.info(f"🎯 找到formUrl控件! (深度{depth})")
                        self.logger.info(f"   名称: {control_name}")
                        self.logger.info(f"   类型: {control_type}")
                        self.logger.info(f"   启用状态: {is_enabled}")
                        input_controls.insert(0, ('🎯 formUrl (主要)', control))

                    # 查找所有输入控件
                    elif control_type == uia.ControlType.EditControl and is_enabled:
                        display_name = f"📝 {control_name or auto_id or f'输入框{len(input_controls)+1}'}"
                        self.logger.info(f"📝 找到输入控件: {control_name} (ID: {auto_id}) (深度{depth})")
                        input_controls.append((display_name, control))

                    # 查找文本输入控件
                    elif control_type == uia.ControlType.DocumentControl and is_enabled:
                        display_name = f"📄 {control_name or auto_id or f'文档控件{len(input_controls)+1}'}"
                        self.logger.info(f"📄 找到文档控件: {control_name} (ID: {auto_id}) (深度{depth})")
                        input_controls.append((display_name, control))

                    # 查找按钮控件 (包括禁用的按钮)
                    elif control_type == uia.ControlType.ButtonControl:
                        # 特别标记创建剪映草稿按钮
                        if '创建剪映草稿' in control_name or '创建' in control_name:
                            self.logger.info(f"🎯 找到主要按钮: {control_name} (深度{depth})")
                            self.logger.info(f"   启用状态: {is_enabled}")
                            button_controls.insert(0, ('🎯 创建剪映草稿 (主要)', control))
                        elif is_enabled and control_name not in ['最小化', '最大化', '关闭']:  # 只记录启用的其他按钮
                            display_name = f"🔘 {control_name or auto_id or f'按钮{len(button_controls)+1}'}"
                            self.logger.info(f"🔘 找到按钮控件: {control_name} (ID: {auto_id}) (深度{depth})")
                            button_controls.append((display_name, control))

                    # 递归查找子控件
                    try:
                        children = control.GetChildren()
                        if children:
                            for child in children:
                                find_recursive(child, depth + 1, max_depth)
                    except:
                        pass

                except Exception as e:
                    pass

            self.logger.info("开始查找控件...")
            find_recursive(self.uia_window)

            self.logger.info(f"📊 扫描结果: {len(input_controls)} 个输入控件, {len(button_controls)} 个按钮")

            # 如果找到了输入控件，就不需要重试了
            if input_controls:
                break

            # 等待页面加载
            if attempt < retry_count - 1:
                self.logger.info(f"未找到输入控件，等待 {wait_time} 秒后重试...")
                time.sleep(wait_time)

        # 选择最佳控件
        input_control = None
        button_control = None

        # 优先选择formUrl输入框
        for name, control in input_controls:
            if 'formUrl' in name:
                input_control = control
                self.logger.info(f"✅ 自动选择了输入控件: {name}")
                break

        if not input_control and input_controls:
            input_control = input_controls[0][1]
            self.logger.info(f"✅ 选择了第一个输入控件: {input_controls[0][0]}")

        # 优先选择创建剪映草稿按钮
        for name, control in button_controls:
            if '创建剪映草稿' in name or '创建' in name:
                button_control = control
                self.logger.info(f"✅ 自动选择了按钮控件: {name}")
                break

        if not button_control and button_controls:
            button_control = button_controls[0][1]
            self.logger.info(f"✅ 选择了第一个按钮控件: {button_controls[0][0]}")

        return input_control, button_control

    def input_url(self, control, url: str) -> bool:
        """向输入框输入URL"""
        try:
            self.logger.info(f"尝试向控件输入URL: {url}")

            # 使用剪贴板方法，避免中文输入法干扰
            old_clipboard = pyperclip.paste() if pyperclip.paste() else ""
            pyperclip.copy(url)
            time.sleep(0.2)

            # 尝试第一个方法：点击并粘贴（带超时保护）
            method_name = "点击并粘贴"
            try:
                self.logger.info(f"尝试方法: {method_name}")

                # 使用线程池执行，设置10秒超时
                with ThreadPoolExecutor(max_workers=1) as executor:
                    future = executor.submit(self._input_method_click_paste, control, url)
                    try:
                        result = future.result(timeout=10.0)
                        if result:
                            self.logger.info(f"✅ {method_name} 成功")
                            # 恢复剪贴板
                            pyperclip.copy(old_clipboard)
                            return True
                        else:
                            self.logger.warning(f"❌ {method_name} 失败")
                    except FuturesTimeoutError:
                        self.logger.error(f"⏱️ {method_name} 超时（10秒），操作被中断")
                        # 恢复剪贴板
                        pyperclip.copy(old_clipboard)
                        return False

            except Exception as e:
                self.logger.error(f"❌ {method_name} 异常: {e}")
                # 恢复剪贴板
                pyperclip.copy(old_clipboard)
                return False

            # 如果第一个方法失败，直接返回失败
            pyperclip.copy(old_clipboard)
            return False

        except Exception as e:
            self.logger.error(f"输入URL失败: {e}")
            return False

    def _input_method_click_paste(self, control, url: str) -> bool:
        """方法1: 点击控件并粘贴"""
        self.logger.info("执行 control.Click()...")
        control.Click()
        self.logger.info("Click() 完成，等待0.5秒")
        time.sleep(0.5)

        self.logger.info("执行 SendKeys(Ctrl+A)...")
        control.SendKeys("{Ctrl}a")
        self.logger.info("Ctrl+A 完成，等待0.2秒")
        time.sleep(0.2)

        self.logger.info("执行 SendKeys(Ctrl+V)...")
        control.SendKeys("{Ctrl}v")
        self.logger.info("Ctrl+V 完成，等待0.8秒")
        time.sleep(0.8)

        self.logger.info("✅ 点击并粘贴方法执行完成")
        return True

    def _input_method_focus_paste(self, control, url: str) -> bool:
        """方法2: 设置焦点并粘贴"""
        control.SetFocus()
        time.sleep(0.5)
        control.SendKeys("{Ctrl}a")
        time.sleep(0.2)
        control.SendKeys("{Ctrl}v")
        time.sleep(0.8)
        return True

    def _input_method_set_value(self, control, url: str) -> bool:
        """方法3: 直接设置值"""
        # 尝试直接设置文本值
        if hasattr(control, 'SetValue'):
            control.SetValue(url)
            time.sleep(0.5)
            return True
        return False

    def _input_method_send_keys(self, control, url: str) -> bool:
        """方法4: 直接发送按键"""
        control.SetFocus()
        time.sleep(0.3)
        # 清空现有内容
        control.SendKeys("{Ctrl}a")
        time.sleep(0.2)
        control.SendKeys("{Delete}")
        time.sleep(0.2)
        # 逐字符输入
        for char in url:
            control.SendKeys(char)
            time.sleep(0.01)
        time.sleep(0.5)
        return True

    def click_button(self, control, wait_for_enable=True, max_wait=10.0) -> bool:
        """点击按钮"""
        try:
            # 检查按钮是否启用，如果需要等待启用
            if wait_for_enable:
                self.logger.info("检查按钮是否启用...")
                start_time = time.time()

                while time.time() - start_time < max_wait:
                    try:
                        is_enabled = getattr(control, 'IsEnabled', True)
                        if is_enabled:
                            self.logger.info("✅ 按钮已启用")
                            break
                        else:
                            self.logger.info("⏳ 按钮未启用，等待中...")
                            time.sleep(0.5)
                    except:
                        # 如果无法检查状态，直接尝试点击
                        break
                else:
                    self.logger.warning("⚠️ 按钮等待超时，强制尝试点击")

            # 尝试多种点击方法，确保点击成功
            click_methods = [
                ("常规点击", lambda: control.Click()),
                ("设置焦点后点击", lambda: (control.SetFocus(), time.sleep(0.2), control.Click())),
                ("双击", lambda: control.DoubleClick()),
                ("右键后左键", lambda: (control.RightClick(), time.sleep(0.1), control.Click()))
            ]

            for method_name, click_method in click_methods:
                try:
                    self.logger.info(f"尝试{method_name}...")
                    click_method()
                    time.sleep(1.0)

                    # 检查是否点击成功（通过检查按钮状态变化）
                    try:
                        is_enabled_after = getattr(control, 'IsEnabled', True)
                        if not is_enabled_after:
                            self.logger.info(f"✅ {method_name}成功 - 按钮已禁用，说明点击生效")
                            return True
                    except:
                        pass

                    self.logger.info(f"✅ {method_name}完成")
                    time.sleep(1.0)  # 给界面一些反应时间
                    return True

                except Exception as e:
                    self.logger.warning(f"❌ {method_name}失败: {e}")
                    continue

            self.logger.error("所有点击方法都失败了")
            return False

        except Exception as e:
            self.logger.error(f"点击按钮失败: {e}")
            return False

    def download_draft(self, url: str, timeout: float = 180.0) -> Dict[str, Any]:
        """下载剪映草稿

        Args:
            url: 剪映草稿的URL地址
            timeout: 下载超时时间（秒）

        Returns:
            包含下载结果的字典
        """
        result = {
            "success": False,
            "message": "",
            "timestamp": datetime.now().isoformat(),
            "url": url
        }

        try:
            self._ensure_com_initialized()
            self.logger.info(f"开始下载剪映草稿: {url}")

            # 1. 查找窗口
            if not self.find_window():
                result["message"] = "未找到剪映小助手窗口"
                self.logger.error(result["message"])
                return result

            # 2. 激活窗口
            if not self.activate_window():
                result["message"] = "激活窗口失败"
                return result

            # 3. 查找控件
            input_control, button_control = self.find_controls()

            if not input_control:
                result["message"] = "未找到URL输入框"
                return result

            if not button_control:
                result["message"] = "未找到创建按钮"
                return result

            # 4. 输入URL
            if not self.input_url(input_control, url):
                result["message"] = "URL输入失败"
                return result

            # 4.5. 验证输入内容
            if not self.verify_input_content(input_control, url):
                result["message"] = "URL输入验证失败，输入框内容不正确"
                return result

            # 等待界面响应
            time.sleep(2.0)

            # 5. 点击按钮（现在输入框有内容，按钮应该更容易点击）
            if not self.click_button(button_control):
                result["message"] = "按钮点击失败"
                return result

            # 6. 等待下载完成
            self.logger.info("等待草稿下载完成...")
            if not self._wait_for_download_complete(timeout):
                result["message"] = f"下载超时或失败，等待时间超过{timeout}秒"
                return result

            result["success"] = True
            result["message"] = "草稿下载成功"
            self.logger.info("剪映草稿下载完成")
            return result

        except Exception as e:
            result["message"] = f"下载异常: {str(e)}"
            self.logger.error(f"下载异常: {str(e)}")
            self.logger.error(f"异常详情: {traceback.format_exc()}")
            return result
        finally:
            self._cleanup_com()

    def _wait_for_download_complete(self, timeout: float = 180.0) -> bool:
        """等待剪映小助手完成草稿下载"""
        start_time = time.time()

        self.logger.info("开始监控剪映小助手下载日志...")

        # 等待策略：
        # 1. 短暂等待，让下载开始
        time.sleep(2.0)

        # 2. 监控下载日志区域的变化
        log_check_interval = 1.5  # 每1.5秒检查一次日志
        last_log_message = ""

        while time.time() - start_time < timeout:
            try:
                # 检查下载日志
                log_info = self._check_download_log()
                current_message = log_info.get('message', '')

                # 如果日志内容发生变化，记录新状态
                if current_message != last_log_message:
                    self.logger.info(f"📋 日志更新: {current_message}")
                    last_log_message = current_message

                # 详细的状态调试信息
                elapsed_time = time.time() - start_time
                self.logger.debug(f"⏱️  等待时间: {elapsed_time:.1f}s, 状态: completed={log_info.get('completed', False)}, error={log_info.get('error', False)}, in_progress={log_info.get('in_progress', False)}")

                # 检查完成状态
                if log_info.get('completed', False):
                    self.logger.info("✅ 下载完成: 剪映草稿已成功下载")
                    # 再等待一点时间确保完全完成
                    time.sleep(1.0)
                    return True

                # 检查错误状态
                elif log_info.get('error', False):
                    self.logger.error(f"❌ 下载失败: {current_message}")
                    return False

                # 如果正在进行中
                elif log_info.get('in_progress', False):
                    self.logger.info(f"⏳ 下载进行中: {current_message}")

                # 如果还是"暂无日志记录"，说明下载可能还没开始
                elif current_message == '暂无日志记录':
                    elapsed = time.time() - start_time
                    if elapsed > 10:  # 如果10秒后还没有日志，可能有问题
                        self.logger.warning("⚠️ 点击按钮后10秒仍无下载日志，可能点击失败")

                time.sleep(log_check_interval)

            except Exception as e:
                self.logger.warning(f"检查下载状态异常: {e}")
                time.sleep(2.0)

        self.logger.warning(f"下载等待超时 ({timeout}秒)")
        return False

    def _check_download_log(self) -> Dict[str, Any]:
        """检查剪映小助手的下载日志区域"""
        try:
            if not self.uia_window:
                return {}

            # 查找日志相关的控件
            log_info = {
                'completed': False,
                'error': False,
                'in_progress': False,
                'message': '暂无日志记录'
            }

            def find_log_area(control, depth=0, max_depth=15):
                if depth > max_depth:
                    return

                try:
                    control_name = getattr(control, 'Name', '') or ''
                    control_type = control.ControlType

                    # 查找下载日志区域的文本内容
                    if control_name and len(control_name) >= 5:  # 过滤掉太短的控件名（按钮、标签等）
                        # 先检查是否是真正的日志消息（包含特定标志）
                        is_log_message = (
                            '下载完成' in control_name or
                            '错误' in control_name or
                            '失败' in control_name or
                            '重试' in control_name or
                            ':' in control_name or  # 日志消息通常包含冒号
                            '暂无日志' in control_name
                        )

                        if is_log_message:
                            # 更新日志消息（但不立即输出，避免重复）
                            log_info['message'] = control_name

                            # 判断具体状态，只在关键状态变化时输出日志
                            if '下载完成: 剪映草稿已成功下载' in control_name:
                                log_info['completed'] = True
                                self.logger.info("✅ 检测到下载完成标志")
                            elif '下载完成' in control_name and '成功' in control_name:
                                log_info['completed'] = True
                                self.logger.info("✅ 检测到下载完成")
                            elif self._is_final_error(control_name):
                                # 只有真正的最终错误才标记为error
                                log_info['error'] = True
                                self.logger.warning(f"❌ 检测到最终下载错误: {control_name}")
                            elif self._is_retry_message(control_name):
                                # 重试消息不算错误，继续等待
                                log_info['in_progress'] = True
                                self.logger.info(f"🔄 检测到重试消息: {control_name}")
                            elif '下载' in control_name and any(kw in control_name for kw in ['进行', '处理', '开始', '%']):
                                # 只有明确表示进度的消息才记录
                                log_info['in_progress'] = True
                                self.logger.debug(f"⏳ 下载进行中: {control_name}")  # 改为debug级别

                        # 特别检查是否还是"暂无日志记录"
                        elif control_name == '暂无日志记录':
                            log_info['message'] = control_name
                            # 保持默认状态

                    # 递归查找子控件
                    try:
                        children = control.GetChildren()
                        if children:
                            for child in children:
                                find_log_area(child, depth + 1, max_depth)
                    except:
                        pass

                except Exception as e:
                    pass

            find_log_area(self.uia_window)
            return log_info

        except Exception as e:
            self.logger.debug(f"检查下载日志异常: {e}")
            return {
                'completed': False,
                'error': False,
                'in_progress': False,
                'message': '检查日志失败'
            }

    def _is_retry_message(self, message: str) -> bool:
        """判断是否是重试消息（不是最终失败）"""
        retry_patterns = [
            '重试',
            'retry',
            '第1次重试',
            '第2次重试',
            '第3次重试',
            '1秒后进行',
            '2秒后进行',
            '3秒后进行',
            'timeout of 15000ms exceeded'  # 这通常是重试前的超时消息
        ]

        for pattern in retry_patterns:
            if pattern in message:
                return True
        return False

    def _is_final_error(self, message: str) -> bool:
        """判断是否是最终的不可恢复错误"""
        final_error_patterns = [
            '下载失败，请重新尝试',
            '网络连接失败',
            '文件不存在',
            '权限不足',
            '无法访问',
            '下载彻底失败',
            '所有重试都失败了',
            '最终失败'
        ]

        # 如果消息包含"失败"但同时包含重试相关内容，不算最终错误
        if '失败' in message:
            if self._is_retry_message(message):
                return False
            # 如果只是简单的"失败"而没有重试信息，可能是最终失败
            # 但我们要更保守一点，只有明确的最终错误词才认为是真正失败
            for pattern in final_error_patterns:
                if pattern in message:
                    return True

        return False

    def verify_input_content(self, control, expected_url: str) -> bool:
        """验证输入框内容是否正确"""
        try:
            # 尝试获取输入框的当前内容
            current_value = ""

            # 方法1: 尝试获取Value属性
            try:
                if hasattr(control, 'CurrentValue'):
                    current_value = control.CurrentValue
                elif hasattr(control, 'Value'):
                    current_value = control.Value
            except:
                pass

            # 方法2: 尝试选择全部内容并复制
            if not current_value:
                try:
                    old_clipboard = pyperclip.paste() if pyperclip.paste() else ""
                    control.SetFocus()
                    time.sleep(0.2)
                    control.SendKeys("{Ctrl}a")
                    time.sleep(0.2)
                    control.SendKeys("{Ctrl}c")
                    time.sleep(0.5)
                    current_value = pyperclip.paste()
                    pyperclip.copy(old_clipboard)  # 恢复剪贴板
                except:
                    pass

            self.logger.info(f"输入框当前内容: {current_value[:100]}...")
            self.logger.info(f"期望内容: {expected_url[:100]}...")

            # 检查内容是否匹配
            if expected_url.strip() in current_value.strip():
                self.logger.info("✅ 输入内容验证成功")
                return True
            else:
                self.logger.warning("❌ 输入内容验证失败")
                return False

        except Exception as e:
            self.logger.error(f"验证输入内容失败: {e}")
            return False

    def check_window_status(self) -> Dict[str, Any]:
        """检查剪映小助手窗口状态"""
        try:
            self._ensure_com_initialized()
            found = self.find_window()
            window_title = win32gui.GetWindowText(self.target_window) if self.target_window else ""

            return {
                "window_found": found,
                "window_title": window_title,
                "timestamp": datetime.now().isoformat()
            }
        except Exception as e:
            return {
                "window_found": False,
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }